package 力扣;

import java.util.HashMap;
// 实现了但是超时
public class LRUCache {
    public static void main(String[] args) {
        LRUCache lruCache=new LRUCache(2);
        System.out.println(lruCache.get(2));
        lruCache.put(2,6);
        System.out.println(lruCache.get(1));
        lruCache.put(1,5);
        lruCache.put(1,2);
        System.out.println(lruCache.get(1));
        System.out.println(lruCache.get(2));
    }

    HashMap<Integer,Integer> map=new HashMap<>();
    HashMap<Integer,Integer> time=new HashMap<>();
    int capacity;
    int usedCapacity;

    public LRUCache(int capacity) {
         this.capacity=capacity;
         usedCapacity=0;
    }





    public int get(int key) {
        if (map.containsKey(key)) {
            // 更新值
            changeTime(key);
            return map.get(key);
        }
        return -1;
    }

    public void changeTime(Integer key){
        // 更新值
        if(time.isEmpty()){
            time.put(key,0);
        }else {
            for (Integer integer : time.keySet()) {
                time.put(integer,time.get(integer)-1);
            }
            time.put(key,0);
        }
    }

    public Integer getLRU(){
        int min=1;
        int key=0;
        for (Integer integer : time.keySet()) {
           if(time.get(integer)<min){
               min=time.get(integer);
               key=integer;
           }
        }
        return key;
    }

    public void put(int key, int value) {
        // 情况一 容量尚未占满
        if(usedCapacity<capacity){
            if(map.containsKey(key)){
                map.put(key,value);
                // 更新值
                changeTime(key);
            }else {
                map.put(key,value);
                usedCapacity++;
                // 更新值
                changeTime(key);
            }
        }else {
            // 情况二 容量已经被占满 需要删除一个最近未使用的
            if(usedCapacity==capacity){
                if(map.containsKey(key)){
                    map.put(key,value);
                    // 更新值
                    changeTime(key);
                }else{
                    Integer lruKey = getLRU();
                    map.remove(lruKey);
                    time.remove(lruKey);
                    map.put(key,value);
                    //更新值
                    changeTime(key);
                }


            }
        }

    }
}
